package com.heima.comment.service.impl;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    GreenScan greenScan;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    UserFeign userFeign;

    /**
     * 保存回复
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {

        //1. 参数校验:
        //   是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        String commentId = dto.getCommentId();  //评论id
        String content = dto.getContent();  //回复内容

        //  阿里云校验评论内容是否违规，过滤掉违规词汇：替换为**
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            if (!scanResult.getSuggestion().equals("pass")) {
                content = scanResult.getFilteredContent();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云 文本审核出现异常");
        }
        //2. 根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(commentId));
        ApComment comment = mongoTemplate.findOne(query, ApComment.class);
        if (comment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3. 保存评论回复信息
        ResponseResult<ApUser> loginUser = userFeign.findUserById(user.getId());
        ApUser userData = loginUser.getData();
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setContent(content);
        apCommentRepay.setCommentId(commentId);
        apCommentRepay.setAuthorId(userData.getId());
        apCommentRepay.setAuthorName(userData.getName());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setLikes(0);
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        //4. 修改评论信息中回复数量 + 1
        comment.setReply(comment.getReply() + 1);
        comment.setUpdatedTime(new Date());
        mongoTemplate.save(comment);
        return ResponseResult.okResult();
    }


    /**
     * 查看更多回复内容
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        //   评论id不能为空   size为null 或 0=>设置为10    最小日期为空=>设置为当前
        String commentId = dto.getCommentId();//评论id
        //   校验size
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        //  校验date
        Date minDate = dto.getMinDate();
        if (minDate == null) {
            minDate = new Date();
        }
        //2. 条件查询评论回复信息
        //	条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        List<ApCommentRepay> apCommentRepayList;
        Query query = Query.query(Criteria.where("commentId").is(commentId).and("createdTime")
                        .lt(minDate)).with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size);
        apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
        //3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        Integer loginId = user.getId();
        //	3.1 如果未登录直接 返回评论回复列表
        if (user == null) {
            return ResponseResult.okResult(apCommentRepayList);
        }
        //	3.2 如果登录，需要判断哪些回复点过赞
        List<ApCommentRepayVO> list = new ArrayList<>();
        //   遍历回复列表
        if (CollectionUtils.isNotEmpty(apCommentRepayList)) {
            for (ApCommentRepay apCommentRepay : apCommentRepayList) {
                ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
                BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
                ApCommentRepayLike apCommentLike = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(loginId).and("commentRepayId").is(apCommentRepay.getId())), ApCommentRepayLike.class);
                if (apCommentLike != null) {
                    apCommentLike.setOperation((short) 0);
                }
                list.add(apCommentRepayVO);
            }
        }
        return ResponseResult.okResult(list);
    }
        //
        //	思路:
        //
        //	     基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        //
        //	     遍历 当前回复列表，将每一个回复信息 封装成 vo
        //
        //	     判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理


        /**
         * 点赞回复的评论
         */
    @Override
    public ResponseResult saveCommentRepayLike (CommentRepayLikeDTO dto){
        //1. 校验参数
        //       回复id不能为空   operation 必须 0 或 1
        String commentRepayId = dto.getCommentRepayId();
        Short operation = dto.getOperation();
        //       校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //       校验回复信息是否存在
        Query queryCommentRepayId = Query.query(Criteria.where("id").is(commentRepayId));
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(queryCommentRepayId, ApCommentRepay.class);
        if (apCommentRepay == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"回复信息不存在");
        }
        //2. 如果是点赞  判断是否点过赞
        Integer loginId = user.getId();
        if (operation == 0) {
            Query queryOperation = Query.query(Criteria.where("commentRepayId").is(commentRepayId).and("authorId").is(loginId));
            ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(queryOperation, ApCommentRepayLike.class);
            //   点过赞提示 请勿重复点赞
            if (commentRepayLike != null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "不能重复点赞");
            }
            //   未点过赞， 保存点赞信息
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(commentRepayId);
            apCommentRepayLike.setAuthorId(loginId);
                apCommentRepayLike.setOperation((short) 0);
                mongoTemplate.save(apCommentRepayLike);
                //       并将回复信息的点赞数量字段+1
                apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
                apCommentRepay.setUpdatedTime(new Date());
            }

        //3. 如果是取消赞
        if (operation == 1){
            //      删除点赞信息
            Query queryOperation = Query.query(Criteria.where("commentRepayId").is(commentRepayId).and("authorId").is(loginId));
            mongoTemplate.remove(queryOperation, ApCommentRepayLike.class);

            //     并将回复信息的点赞数量字段-1
            if (apCommentRepay.getLikes() <=0){
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "点赞数量出错");
            }
            apCommentRepay.setLikes(apCommentRepay.getLikes() - 1);
            apCommentRepay.setUpdatedTime(new Date());
            mongoTemplate.save(apCommentRepay);
        }

        //4. 返回当前回复的最新点赞数量      数据的key:  likes
        Map map = new HashMap<>();
        map.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(map);
    }

}